<%@ page import="java.util.Random" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>自出题计算器</title>
</head>
<body>
<%
    String num1 = "";
    String num2 = "";
    char op = '+';
    String type = "0";
    String msg = "";
    String userResult = "";
    char[] sop = new char[]{'+', '-', '*', '/'};
    num1 = request.getParameter("num1") == null ? num1 : request.getParameter("num1");
    num2 = request.getParameter("num2") == null ? num2 : request.getParameter("num2");
    op = request.getParameter("op") == null ? op : request.getParameter("op").charAt(0);
    type = request.getParameter("type") == null ? type : request.getParameter("type");
    userResult = request.getParameter("userNum") == null ? userResult : request.getParameter("userNum");
    if ("1".equals(type) && !"".equals(num1) && !"".equals(num2)) {
        int s1 = Integer.parseInt(num1);
        int s2 = Integer.parseInt(num2);
        int sum = 0;
        switch (op) {
            case '+':
                sum = s1 + s2;
                break;
            case '-':
                sum = s1 - s2;
                break;
            case '*':
                sum = s1 * s2;
                break;
            case '/':
                sum = s1 / s2;
                break;
        }
        if (userResult != null) {
            int userInput = 0;
            try {
                userInput = Integer.parseInt(userResult);
            } catch (NumberFormatException ignored) {

            }
            if (userInput == sum)
                msg = "正确";
            else
                msg = "错误";
        }
    } else if ("2".equals(type)) {
        Random random = new Random();
        int opNum = random.nextInt(4);
        if (opNum == 3) {
            int a = 10;
            int b = 3;
            while (a * b > 20) {
                a = random.nextInt(10) + 1;
                b = random.nextInt(5) + 1;
            }
            num1 = a * b + "";
            num2 = b + "";
        } else {
            num1 = random.nextInt(20) + "";
            num2 = random.nextInt(20) + "";
        }
        op = sop[opNum];
        userResult = "";
    }
%>
<p style="color:red;"><%=msg%>
</p>
<form method="post">
    <%=num1%>
    <%=op%>
    <%=num2%>
    =
    <input name="userNum" type="text" value="<%=userResult%>"><br/>
    <input name="num1" type="hidden" value="<%=num1%>">
    <input name="op" type="hidden" value="<%=op%>">
    <input name="num2" type="hidden" value="<%=num2%>">
    <input name="type" id="type" type="hidden" value="0">
    <input type="submit" value="评分" onclick="setType(1)">
    <input type="submit" value="出题" onclick="setType(2)">
</form>
<script>
    function setType(a) {
        document.getElementById("type").value = a
    }
</script>
</body>
</html>
